<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2019/1/10
 * Time: 15:17
 */

namespace api\storage\service\input;

use api\storage\common\Constant;
use api\storage\model\SeatModel;
use api\storage\model\ShelvesModel;
use api\storage\service\SocketService;

class WhiteInputService extends BaseInputService
{
    public function afterHandle($userId, $type, $storageUuid)
    {
        $seat = $this->findSeatCode($userId, $type, $storageUuid);
        if (empty($seat)) {
            return $this->resultTemplate(0);
        }
        SocketService::send($seat['seat_id'], $storageUuid, Constant::TURN_ON_GREEN);
        return $this->resultTemplate(1, $this->dataTemplate($this->materielId, $seat['seat_code'], $this->count));
    }

    public function checkSeatCode($seatCode, $storageUuid)
    {
        $seatModel = new SeatModel();
        $seat = $seatModel->findByCodeAndStorageUuid($seatCode, $storageUuid);
        if (empty($seat) || empty($seat->getData())) {
            return $this->resultTemplate(-1);
        }
        return $this->resultTemplate(1, ['seat_id' => $seat->getData('seat_id')]);
    }


    /**
     * 查找站位
     *
     * @param $userId
     * @param $type
     * @param $uuid
     * @return array|null
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function findSeatCode($userId, $type, $uuid)
    {
        //查找绑定的货架
        $shelf = $this->shelvesModel->findByUserIdAndUuid($userId, $uuid);
        if (empty($shelf) || empty($shelf->getData())) {
            //没有绑定的的话，找一个货架来推站位
            $seat = $this->findSeatCodeByShelf($userId, $type, $uuid);
        } else {
            //有的话，在绑定的货架上找站位
            $seat = $this->findSeatCodeByUser($shelf->getData('uuid'), $userId, $type, $uuid);
        }
        return $seat;
    }

    /**
     * 实现父类操作，查找用户绑定的货架
     *
     * @param $userId
     * @param $storageUuid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lookingBindShelf($userId, $storageUuid)
    {
        $shelvesModel = new ShelvesModel();
        $data = $shelvesModel->findByUserIdAndUuid($userId, $storageUuid);
        if ($this->isNotEmpty($data)) {
            return $this->resultTemplate(1, ['shelfCode' => $data->getData('shelves_code')]);
        }
        return $this->resultTemplate(0);
    }

    public function bindShelf($seatCode, $userId, $storageUuid)
    {
        //查看站位
        $seatModel = new SeatModel();
        $seat = $seatModel->findByCodeAndStorageUuid($seatCode, $storageUuid);
        if ($this->isEmpty($seat)) {
            return $this->resultTemplate(-3);
        }
        //查看货架
        $shelfUuid = $seat->getData('shelves_uuid');
        $shelf = $this->shelvesModel->findByUuid($shelfUuid);
        if ($this->isEmpty($shelf)) {
            return $this->resultTemplate(-2);
        }
        //是否已经被绑定
        $dbUserId = $shelf->getData('user_id');
        if (!empty($dbUserId) && $dbUserId != $userId) {
            return $this->resultTemplate(-1);
        }
        //重复绑定算绑定成功
        if ($dbUserId == $userId) {
            return $this->resultTemplate(1);
        }
        //已经绑定一个货架，需要先解绑
        $existShelf = $this->shelvesModel->findByUserIdAndUuid($userId, $storageUuid);
        if ($this->isNotEmpty($existShelf)) {
            return $this->resultTemplate(-4);
        }
        $this->shelvesModel->updateUserId($shelfUuid, $userId);
        return $this->resultTemplate(1);
    }

    public function unbindShelf($userId, $storageUuid)
    {
        $shelf = $this->shelvesModel->findByUserIdAndUuid($userId, $storageUuid);
        if (empty($shelf) || empty($shelf->getData()) || empty($shelf->getData('user_id'))) {
            return $this->resultTemplate(1);
        }
        $this->shelvesModel->updateUserId($shelf->getData('uuid'));
        return $this->resultTemplate(1);
    }

    /**
     *  用户没有绑定货架查找站位
     *
     * @param $userId
     * @param $type
     * @param $uuid
     * @return array|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function findSeatCodeByShelf($userId, $type, $uuid)
    {
        $data = $this->shelvesModel->findSeatCodeWithSeat($type, $uuid);
        if ($this->isEmpty($data)) {
            return null;
        } else {
            //如果数据不为空，需要绑定用户货架
            $shelfUuid = $data->getData('shelves_uuid');
            $this->shelvesModel->updateUserId($shelfUuid, $userId);
            $this->logger->debug("用户Id：{$userId}，默认绑定货架：{$shelfUuid}");
            return ['seat_id' => $data->getData('seat_id'), 'seat_code' => $data->getData('seat_code')];
        }
    }

    /**
     *  用户绑定货架查找站位
     *
     * @param $shelfUuid
     * @param $userId
     * @param $type
     * @param $uuid
     * @return array|null
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function findSeatCodeByUser($shelfUuid, $userId, $type, $uuid)
    {
        $seatModel = new SeatModel();
        $seat = $seatModel->findSeatCodeByShelfUuid($shelfUuid);
        if (empty($seat)) {
            //清除绑定
            $this->shelvesModel->updateUserId($shelfUuid);
            $this->logger->debug("用户：{$userId}，在绑定货架：{$shelfUuid}上没有找到合适站位，默认清除绑定");
            $seat = $this->findSeatCodeByShelf($userId, $type, $uuid);
            if(empty($seat)){
                $this->logger->debug("用户：{$userId}，在仓库里没有找到合适站位");
                return null;
            }
        }

        $seat->toArray();
        return $seat;
    }
}